package com.mybook.app.service;

import com.mybook.app.conf.WxConfig;
import com.mybook.app.error.Error;
import com.mybook.app.exception.WxMinaException;
import com.mybook.app.feign.MinaFeignClient;
import com.mybook.app.mapper.UserInfoMapper;
import com.mybook.app.model.UserInfo;
import com.mybook.app.request.WxLoginRequest;
import com.mybook.app.response.MinaAccessTokenResponse;
import com.mybook.app.response.WxLoginResponse;
import com.mybook.app.utils.IdUtils;
import com.mybook.app.utils.JsonUtil;
import com.mybook.app.utils.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;

@Service
public class MinaService {

    @Autowired
    private MinaFeignClient minaFeignClient;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 微信授权登录
     *
     * @param wxLoginRequest
     */
    public WxLoginResponse onLogin(WxLoginRequest wxLoginRequest) {


        // 通过code换取网页授权session_key
        //从微信服务器获得session_key,openid,unionidw
        String resp = minaFeignClient.jscode2session(wxConfig.getAppid(), wxConfig.getSecret(), wxLoginRequest.getCode(), wxConfig.getGrantType());
        MinaAccessTokenResponse minaAccessTokenResponse = JsonUtil.toObject(MinaAccessTokenResponse.class, resp);
        if (null != minaAccessTokenResponse && null != minaAccessTokenResponse.getErrcode()) {
            // 抛出对应的错误码
            Logger.info(this, "微信授权失败：" + minaAccessTokenResponse);
            throw new WxMinaException(Error.WX_AUTHORIZATION, minaAccessTokenResponse.getErrmsg());
        }
        UserInfo userInfo = userInfoMapper.findUserInfoDetailByWxId(minaAccessTokenResponse.getOpenId());
        String id = IdUtils.getId(wxLoginRequest.getCity());
        //判断是否存在
        if (null == userInfo) {
            userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setStar(0);
            userInfo.setcTime(new Date());
            userInfo.setuTime(new Date());
            try {
                String name = URLDecoder.decode(wxLoginRequest.getAlias(), "utf-8");
                userInfo.setAlias(name);
                userInfo.setName(name);
            } catch (UnsupportedEncodingException ex) {
                Logger.warn(this, "转码错误", ex);
                userInfo.setAlias(wxLoginRequest.getAlias());
                userInfo.setName(wxLoginRequest.getAlias());
            }
            userInfo.setCity(wxLoginRequest.getCity());
            userInfo.setCountry(wxLoginRequest.getCountry());
            userInfo.setProvince(wxLoginRequest.getProvince());
            userInfo.setWxIcon(wxLoginRequest.getWxIcon());
            userInfo.setSex(wxLoginRequest.getSex());
            //微信返回的相关信息
            userInfo.setWxId(minaAccessTokenResponse.getOpenId());
            userInfo.setSessionKey(minaAccessTokenResponse.getSessionKey());
            userInfo.setWxUuid(minaAccessTokenResponse.getUnionId());
            userInfo.setOpenId(minaAccessTokenResponse.getOpenId());
            int row = userInfoMapper.insertSelective(userInfo);
            Logger.info(this, "用户插入数据成功 ：" + row);
        } else {
            userInfo.setuTime(new Date());
            try {
                userInfo.setAlias(URLDecoder.decode(wxLoginRequest.getAlias(), "utf-8"));
            } catch (UnsupportedEncodingException ex) {
                Logger.warn(this, "转码错误", ex);
            }
            userInfo.setCity(wxLoginRequest.getCity());
            userInfo.setCountry(wxLoginRequest.getCountry());
            userInfo.setProvince(wxLoginRequest.getProvince());
            userInfo.setWxIcon(wxLoginRequest.getWxIcon());
            userInfo.setSex(wxLoginRequest.getSex());
            //微信返回的相关信息
            userInfo.setSessionKey(minaAccessTokenResponse.getSessionKey());
            userInfo.setWxUuid(minaAccessTokenResponse.getUnionId());
            int row = userInfoMapper.updateUserInfoById(userInfo);
            Logger.info(this, "更新用户数据成功：" + row);
        }
        WxLoginResponse wxLoginResponse = new WxLoginResponse();
        wxLoginResponse.setUserId(userInfo.getId());
        wxLoginResponse.setOpenId(minaAccessTokenResponse.getOpenId());
        wxLoginResponse.setSessionKey(minaAccessTokenResponse.getSessionKey());

        return wxLoginResponse;
    }


}
